package com.interagriculture.utils;

import com.interagriculture.common.Constants;
import com.interagriculture.common.CustomException;
import com.interagriculture.common.FilePathConstants;
import com.interagriculture.entity.UserInfo;
import com.interagriculture.enums.ExceptionCodeEnum;
import com.interagriculture.enums.PictureTypeEnum;
import com.interagriculture.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.UUID;

/**
 * 上传图片存入图片工具
 * @author 10 2024/10/24
 */
@Component
@Slf4j
public class UploadFileUtil {
     @Value("${file.upload.path}")
     private String filePath;

     /**
      * 存入图片
      * @param picture
      * @return
      */
     public String uploadUserFile(Integer type,Integer userId,MultipartFile picture)  {
          if(picture==null){
               return null;
          }
          String path = filePath+ PictureTypeEnum.getFilePath(type)+"\\"+userId;
          File file = new File(path);
          if(!file.exists()){
               file.mkdirs();
          }
          String searchPath = userId + FilePathConstants.图片后缀;

          try {
               picture.transferTo(new File(file,searchPath));
          } catch (IOException e) {
               e.printStackTrace();
          }
          return searchPath;
     }

     public void removePicture(Integer type,Integer userId,String picturePath){
          String fileMidPath = PictureTypeEnum.getFilePath(type);
          String pathMid = filePath+fileMidPath+ userId ;//+picturePath

          Path paths = Paths.get(pathMid);
          try {
               Files.walk(paths)
                       .sorted(Comparator.reverseOrder())
                       .map(path ->{
                            try {
                                 return Files.deleteIfExists(path);
                            } catch (IOException e) {
                                 log.error("文件删除错误...");
                                throw new RuntimeException(e);
                            }
                       })
                       .forEach(deleted->{
                            if(deleted){
                                 System.out.println("已删除: " + deleted);
                                 log.info("已删除: {}" ,deleted);
                            }
                       });
          } catch (IOException e) {
               log.debug("文件夹删除问题");
               throw new CustomException(ExceptionCodeEnum.DELETE_ERROR);
          }
     }

}
